﻿namespace YABE.Controllers
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using System.ServiceModel.Syndication;
    using System.Configuration;

    using YABE.ActionResults;

	public class FeedsController : Controller
	{

        private Models.PostDL pd;

        public FeedsController()
        {
            this.pd = new YABE.Models.PostDL();
        }

		public ActionResult rss20()
		{
            return new RssResult(GetFeed());
		}

		public ActionResult atom()
		{
            return new AtomResult(GetFeed());
		}

		private SyndicationFeed GetFeed()
		{
			List<YABE.Models.Post> recentPosts = pd.GetRecentPosts(20);

			SyndicationFeed feed = new SyndicationFeed(
				ConfigurationManager.AppSettings["BlogTitle"],
				ConfigurationManager.AppSettings["BlogDescription"], 
				new Uri(ConfigurationManager.AppSettings["SyndicationAlternateUri"]));
            feed.Authors.Add(new SyndicationPerson(
				ConfigurationManager.AppSettings["SyndicationEmail"]));
            feed.Categories.Add(new SyndicationCategory(
				ConfigurationManager.AppSettings["SyndicationCategory"]));
            feed.Description = new TextSyndicationContent(
				ConfigurationManager.AppSettings["SyndicationContent"]);
            
            //Adding Items
			//Adding the items to the list of generic syndication items.
            List<SyndicationItem> items = new List<SyndicationItem>();


			foreach (Models.Post p in recentPosts)
			{
				TextSyndicationContent content = new TextSyndicationContent(p.Body,
					TextSyndicationContentKind.Html );
				
				SyndicationItem item = new SyndicationItem(
				p.Title, content,
				new Uri(p.Url),
				p.PostID.ToString(),
				p.Modified);

				items.Add(item);
			}
            
            feed.Items = items;

			return feed;
		}
	}
}
